package com.ferris.ioc;
import android.app.Activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class UIBindUtil {

	/**
	 * 绑定初始化各个空间的属性以及事件
	 * @param activity
	 */
	public static void bind(Activity activity) {
		Class<?> cl = activity.getClass();
		bindViews(activity, cl);
		bindMethods(activity, cl);
	}
	
	
	/**
	 *  为按钮绑定对应的事件方法
	 * @param activity
	 * @param cl
	 */
	private static void bindMethods(Activity activity, Class<?> cl) {
		for (Method method : cl.getDeclaredMethods()) {
			ClickMethod oc = method.getAnnotation(ClickMethod.class);
			if (oc != null) {
				int ids[] = oc.value();
				for (int id : ids) {
					OnEventListener listener = new OnEventListener(activity)
					.setmClick(id,method.getName());
					activity.findViewById(id).setOnClickListener(listener);
				}
			}
		}
	}
	/**
	 *  初始化按钮
	 * @param activity
	 * @param cl
	 */
	private static void bindViews(Activity activity, Class<?> cl) {
		try {
			for (Field field : cl.getDeclaredFields()) {
				InjectView av = field.getAnnotation(InjectView.class);
				if (av != null) {
					field.setAccessible(true);
					setView(field, activity, av.id());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private static void setView(Field view, Activity activity, int id)
			throws IllegalArgumentException, IllegalAccessException {
		view.set(activity, activity.findViewById(id));
	}
	

}